package handler

import (
	"encoding/json"
	"post-master/cache"
	"post-master/model"
	"time"

	"github.com/gin-gonic/gin"
)

func Add(c *gin.Context) {

	var title = c.PostForm("title")
	var desc = c.PostForm("desc")
	var author = c.PostForm("author")

	if title == "" || desc == "" || author == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}

	a := model.Article{
		Title:  title,
		Desc:   desc,
		Author: author,
	}

	err := model.DB.Debug().Create(&a).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "数据添加失败",
		})
		return
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "add",
	})
	return
}

func Del(c *gin.Context) {

	id := c.PostForm("id")

	err := model.DB.Debug().Where("id = ?", id).Delete(&model.Article{}).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "删除失败",
		})
		return
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
	return

}

func List(c *gin.Context) {

	var a []model.Article

	//设置redis的KYE
	redis_list_key := "list_article"
	result, _ := cache.Rdb.Get(cache.Ctx, redis_list_key).Result()
	if result == "" {
		// 从mysql数据
		model.DB.Debug().Find(&a)
		// 设置到缓存redis中
		jsonData, _ := json.Marshal(a)
		cache.Rdb.Set(cache.Ctx, redis_list_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(result), &a)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "成功",
		"data": a,
	})
	return

}
